package com.example.entity;

/**
 * @Author: wyp
 * @Date: 2021/9/8 14:02
 * 单例模式Bean
 * 采用DCL（Double Check Lock）双端检测机制
 * 由于存在指令重排的问题，new SingletonBean()底层执行3个操作:new -> dup -> invokespecial，不可颠倒，需要给singletonBean加volatile。
 */
public class SingletonBean {
    private static volatile SingletonBean singletonBean = null;

    private SingletonBean(){
        System.out.println(Thread.currentThread().getName()+"线程，SingletonBean单例模式只会调用一次无参构造！");
    }

    public static SingletonBean getInstance(){
        if(singletonBean == null){
            synchronized (SingletonBean.class){
                if(singletonBean == null){
                    singletonBean = new SingletonBean();
                }
            }
        }
        return singletonBean;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                SingletonBean.getInstance();
            },String.valueOf(i)).start();
        }

    }
}
